#!/usr/bin/env ruby
#coding:utf-8
$KCODE='u' if RUBY_VERSION<'1.9'

Picrawler_gateway_path="Picrawler.rb" ###

###main
require "optparse"
require "fileutils"
STDOUT.sync = true

def pcrawl(argv)
Dir.chdir(File.dirname(__FILE__))

require File.expand_path(Picrawler_gateway_path) ### Picrawler module path ###
pic=Picrawler.new(File.expand_path("Picrawler.ini"),lambda{|mes|print mes.encode(@encoding,"UTF-8")});@encoding=pic.encoding

#parse ARGV
mode=[]
options={
	:dir=>nil,
	:arg=>nil,
	:bookmark=>0,
	:fast=>false,
	:start=>1,
	:stop=>-1,
	:filter=>[],
	:additional=>'',
}
OptionParser.new{|opt| #todo: trap Exception and show message in proper way
	opt.banner=
		"Usage: "+opt.program_name+" [options] COMMAND\n"+
		"COMMAND is SITE [MODE ARG]\n"+
		"ex) PiXA -> list available MODE of PiXA\n"+
		"ex) PiXA tag foobar -> crawl PiXA's tag foobar\n"
	opt.on('-l','--list','show illust websites (module names)'){|v| pic.list.each{|e| puts e};exit }
	#opt.on('-i VAL','--id','illustrator id'){|v| options[:id]=v}
	#opt.on('-t VAL','--tag','illust tag'){|v| options[:tag]=v}
	opt.on('-d VAL','--dir','save dir'){|v| options[:dir]=v}
	opt.on('-b VAL','--bookmark','bookmark number'){|v| options[:bookmark]=v.to_i}
	opt.on('-s VAL','--start','starting page (>=1)'){|v| options[:start]=v.to_i;if options[:start]<1 then raise "starting page must be 1 or bigger" end}
	opt.on('-e VAL','--end','ending page'){|v| options[:stop]=v.to_i}
	opt.on('-f','--fast','fast mode: stops immediately when duplicated'){|v| options[:fast]=true}
	opt.on('-h','--help','show this message'){|v| puts "Picrawler"+" "+Version;puts opt;exit}
	opt.on('-v','--version','print version'){|v| puts "Picrawler"+" "+Version;exit} #File.basename($0)
	if argv.length==0 then puts "Picrawler"+" "+Version;puts opt;exit end
	mode=opt.parse(argv.map{|e| e.encode("UTF-8",@encoding)})
	#if mode.length==0 then raise "SITE is mandatory." end
	if mode.length==1 then pic.mode_list(mode[0]).each{|e| puts e};exit end
	if mode.length!=3 then raise "COMMAND is SITE [MODE ARG]" end
	options[:arg]=mode[2]
	if options[:stop]>=0 && options[:start]>options[:stop] then raise "Not fulfilling the rule; starting page <= ending page" end
}

pic.pcrawl(mode[0],mode[1],options)
end

pcrawl(ARGV) if __FILE__==$0
